package com.geese.common.shiro.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.geese.common.PropertiesService;
import com.geese.common.constants.Constants;
import com.geese.common.constants.ResponseConstants;
import com.geese.common.shiro.realm.StatelessToken;
import com.geese.common.util.JSONUtil;
import com.geese.exception.ErrorResult;

public class StatelessAuthcFilter extends AccessControlFilter {
	
	private static Logger logger = LoggerFactory.getLogger(StatelessAuthcFilter.class);
	
	@Autowired
	private PropertiesService propertiesService;

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return false;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        //1、客户端生成的消息摘要
        String loginToken = request.getParameter(Constants.TOKEN);
        System.err.println("StatelessAuthcFilter : " + loginToken);
        StatelessToken token = new StatelessToken(loginToken);
        try {
            //5、委托给Realm进行登录
            getSubject(request, response).login(token);
        } catch (Exception e) {
        	logger.error("login error", e);
            onLoginFail(response, ResponseConstants.USER_NOT_LOGIN); //6、token校验失败
            return false;
        }
        return true;
    }

    //token校验失败
    private void onLoginFail(ServletResponse response, int code) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        ErrorResult result = new ErrorResult(code, propertiesService.getProperty(String.valueOf(code)));
        httpResponse.getWriter().write(JSONUtil.objectToJson(result));
    }
}
